// 处方综合管理
import { useEffect, useState } from "react";
import { Space, Table, Pagination, Modal } from "antd";
const { Column } = Table;

import moduleCss from "../../../styles/PrescriptionManagement.module.css";

import {
  Checkprescriptions,
  Prescriptiondetails,
} from "../../../request/zwyApi";
import "../../../assets/zwyAssets/zwyiconfont/iconfont.css";

function PrescriptionManagement() {
  // 定义状态来存储表格数据
  const [tableData, setTableData] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [total, setTotal] = useState(0);
  const showTotal = (total) => `共 ${total} 条`;

  // 对话框相关状态
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);

  // 状态来存储处方详情数据
  const [prescriptionDetails, setPrescriptionDetails] = useState([]);

  // 使用 useEffect 钩子在组件加载时调用 API
  useEffect(() => {
    Checkprescriptions({ page: currentPage, size: pageSize })
      .then((res) => {
        setTableData(res.data);
        setTotal(res.total);
      })
      .catch((error) => {
        console.error("Error fetching data:", error);
      });
  }, [currentPage, pageSize]);

  const handleTableChange = (pagination) => {
    setCurrentPage(pagination.current);
    setPageSize(pagination.pageSize);
  };

  // 图标点击事件处理函数
  function handleIconClick(record) {
    Prescriptiondetails({ id: record.id })
      .then((res) => {
        if (res.code === 1) {
          try {
            // 首先将单引号替换为双引号，并确保字符串中的特殊字符被正确转义
            let recipelString = res.data[0].recipel;
            // 替换单引号为双引号，并处理转义字符
            recipelString = recipelString
              .replace(/'/g, '"')
              .replace(/\\"/g, '"');
            // 解析格式化后的 JSON 字符串
            const recipelData = JSON.parse(recipelString);
            setPrescriptionDetails(recipelData); // 设置处方详情数据
            setCurrentRecord(record);
            setIsModalOpen(true); // 显示对话框
          } catch (error) {
            console.error("Error parsing recipel JSON:", error);
          }
        } else {
          console.error("获取处方详情失败:", res.msg);
        }
      })
      .catch((error) => {
        console.error("Error fetching prescription details:", error);
      });
  }

  // 对话框确认和取消事件处理函数
  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  return (
    <div className={moduleCss.box}>
      <Table
        dataSource={tableData}
        pagination={false}
        onChange={handleTableChange}
        rowKey="id"
        className={moduleCss.tablebox}
      >
        <Column
          title="医生头像"
          dataIndex="head"
          key="avatar"
          render={(text) => (
            <div style={{ width: "50px", height: "50px" }}>
              <img
                src={text}
                alt="医生头像"
                style={{ width: "100%", height: "100%", borderRadius: "10px" }}
              />
            </div>
          )}
        />
        <Column title="医生名称" dataIndex="name" key="address" />
        <Column title="科室" dataIndex="department" key="address" />
        <Column title="处方金额" dataIndex="price" key="address" />

        <Column
          title="操作"
          key="action"
          render={(_, record) => (
            <Space size="middle">
              <i
                className="iconfont icon-wj-wj-1 zwyControls"
                style={{ color: "#50A6FF", cursor: "pointer" }}
                onClick={() => handleIconClick(record)}
              ></i>
            </Space>
          )}
        />
      </Table>
      <Pagination
        size="small"
        current={currentPage}
        total={total}
        showTotal={showTotal}
        showQuickJumper
        showSizeChanger
        defaultPageSize={5}
        pageSizeOptions={["5", "10", "15", "20"]}
        onShowSizeChange={(current, size) => setPageSize(size)}
        onChange={setCurrentPage}
        className={moduleCss.mg}
      />

      {/* 对话框组件 */}
      <Modal
        title="处方详情"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        width={1000}
        footer={null}
      >
        {prescriptionDetails && prescriptionDetails.length > 0 && (
          <>
            <Table
              dataSource={prescriptionDetails}
              pagination={false}
              rowKey="id"
            >
              <Column title="药品名称" dataIndex="drugsname" key="drugsname" />
              <Column title="类别" dataIndex="sort" key="sort" />
              <Column title="规格" dataIndex="type" key="type" />
              <Column title="开始时间" dataIndex="starttime" key="starttime" />
              <Column title="结束时间" dataIndex="endtime" key="endtime" />
              <Column title="数量" dataIndex="count" key="count" />
              <Column title="单价" dataIndex="price" key="price" />
              <Column
                title="图片"
                dataIndex="img"
                key="img"
                render={(text) => (
                  <img
                    src={text}
                    alt="药品图片"
                    style={{ width: "50px", height: "50px" }}
                  />
                )}
              />
              <Column title="用量备注" dataIndex="other" key="other" />
            </Table>
            <div className={moduleCss.priceContainer}>
              <p>总价: {currentRecord.price} </p>
            </div>
          </>
        )}
      </Modal>
    </div>
  );
}

export default PrescriptionManagement;
